from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from djwheel.langutils import cache_method_value
from utils import get_max, get_min, get_prev_item, get_next_item

class OrderingModel(models.Model):
    order = models.PositiveIntegerField(_('order'), default=0, editable=False)

    @classmethod
    def objects_filter(cls):
        return cls.objects.all()

    @cache_method_value
    def is_first(self):
        return self.order == get_min(self.objects_filter(), 'order')

    @cache_method_value
    def is_last(self):
        return self.order == get_max(self.objects_filter(), 'order')

    @cache_method_value
    def prev(self):
        return get_prev_item(self.objects_filter(), 'order', self.order)

    @cache_method_value
    def next(self):
        return get_next_item(self.objects_filter(), 'order', self.order)

    def adm_move_up(self):
        try:
            if self.is_first():
                return ''
            else:
                return '<a href="move_up/%s/%s" style="white-space:nowrap"><img src="%simg/admin/arrow-up.gif" border="0"> %s</a>' % (
                    self.pk, '', settings.ADMIN_MEDIA_PREFIX, _('up'))
        except Exception, e:
            print e
    adm_move_up.allow_tags = True
    adm_move_up.short_description = ''

    def adm_move_down(self):
        if self.is_last():
            return ''
        else:
            return '<a href="move_down/%s/%s" style="white-space:nowrap"><img src="%simg/admin/arrow-down.gif" border="0" alt=""> %s</a>' % (
                self.pk, '', settings.ADMIN_MEDIA_PREFIX, _('down'))
    adm_move_down.allow_tags = True
    adm_move_down.short_description = ''

    class Meta:
        abstract = True
        ordering = ('order',)

